#ifndef LOCKGUARD_H_
#define LOCKGUARD_H_

#include <pthread.h>

class LockGuard {

private:
	pthread_mutex_t* m_mutex;

public:
    LockGuard() 
    : m_mutex(NULL) {
    }

	LockGuard(pthread_mutex_t& mutex)
	: m_mutex(&mutex) {	
	
		pthread_mutex_lock(m_mutex);
	}
	~LockGuard() {
	
		if(m_mutex) pthread_mutex_unlock(m_mutex);
        m_mutex = NULL;
	}

	void reset() {
	
		pthread_mutex_unlock(m_mutex);
		m_mutex = NULL;
	}

	void set(pthread_mutex_t& mutex) {

		m_mutex = &mutex;
		pthread_mutex_lock(m_mutex);
	}
};


class RWLockGuard {

private:
    pthread_rwlock_t* m_rwlock;
    char m_type;

public:
    RWLockGuard(pthread_rwlock_t& rwlock, char type) {
    
        set(rwlock, type);            
    }

    ~RWLockGuard() {
    
        if(m_rwlock) reset();
    }

    void reset() {
    
        pthread_rwlock_unlock(m_rwlock);
        m_rwlock = NULL;
        m_type = 0;
    }

    void set(pthread_rwlock_t& rwlock, char type) {
    
        m_rwlock = &rwlock; m_type = type;

        if(type == 'r')
            pthread_rwlock_rdlock(m_rwlock);
        else
            pthread_rwlock_wrlock(m_rwlock);

    }
};

#endif

